package com.lingjtx.common.security.strategy;

import com.lingjtx.common.core.RedisOptions;
import com.lingjtx.common.core.ResponseResult;
import com.lingjtx.common.core.constant.Const;
import com.lingjtx.common.core.token.AuthToken;
import com.lingjtx.common.core.util.StringUtil;
import com.lingjtx.common.core.annotation.IgnoreLogin;
import com.lingjtx.common.core.token.IgnoreType;
import com.lingjtx.common.security.model.LoginPo;
import com.lingjtx.common.security.limit.HandlerState;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
public class LogoutPolicy extends HandlerState<ProceedingJoinPoint, HttpServletRequest> {


    private LoginLogCallback callback;

    public LoginLogCallback getCallback() {
        return callback;
    }

    public void setCallback(LoginLogCallback callback) {
        this.callback = callback;
    }

    @Override
    public ResponseResult<Object> retError() {
        return ResponseResult.createByError();
    }

    @Override
    public void handler(ProceedingJoinPoint point, HttpServletRequest request, RedisOptions redis) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        IgnoreLogin annotation = signature.getMethod().getAnnotation(IgnoreLogin.class);
        if (Objects.nonNull(annotation) && IgnoreType.LOGOUT.equals(annotation.value())) {
            String token = request.getHeader(Const.AuthTokenMap.AUTHORIZATION);
            if (StringUtil.isNotEmpty(token)) {
                AuthToken.logout(token, redis);
                if (callback != null) {
                    callback.insertLoginLog(request, null, null);
                }
            }
        }
    }

    public interface LoginLogCallback {
        void insertLoginLog(HttpServletRequest request, Long userId, LoginPo loginPo);
    }

}
